

#include <algorithm>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>
#include <vector>

#include <range/v3/range/conversion.hpp>
#include <range/v3/view/transform.hpp>

namespace fs = std::filesystem;

int f(int previous_count, char c)
{
    return (c != '\n') ? previous_count : previous_count + 1;
}

int count_lines(const std::string& filename)
{
    std::ifstream in(filename);
    return std::accumulate(std::istreambuf_iterator<char>(in),
        std::istreambuf_iterator<char>(), 0, f);
    // return std::count(std::istreambuf_iterator<char>(in),
    //     std::istreambuf_iterator<char>(), '\n');
}

std::vector<int> count_lines_in_files(const std::vector<std::string>& files)
{
    return files | ranges::views::transform(count_lines) | ranges::to<std::vector<int>>();
}

int main()
{
    std::string dir = "/usr/include/";
    std::vector<std::string> header_files;
    // 使用 std::filesystem 遍历目录
    try {
        // 遍历目录
        for (const auto& entry : fs::directory_iterator(dir)) {
            // 检查是否是一个文件并且扩展名是 .h
            if (entry.is_regular_file() && entry.path().extension() == ".h") {
                // 获取绝对路径并加入 vector
                header_files.push_back(entry.path().string());
            }
        }

        // // 打印所有找到的 .h 文件的绝对路径
        // std::cout << "Found .h files:" << std::endl;
        // for (const auto &file : header_files) {
        //   std::cout << file << std::endl;
        // }
    } catch (const std::exception& e) {
        std::cerr << "Error accessing directory: " << e.what() << std::endl;
    }

    auto results = count_lines_in_files(header_files);
    for (size_t i = 0; i < results.size(); ++i) {
        std::cout << header_files[i] << " : " << results[i] << std::endl;
    }
}